<template>
  <view class="classLayout pageBg">
    <!-- #ifndef MP-TOUTIAO -->
    <custom-nav-bar title="分类"></custom-nav-bar>
    <!-- #endif -->

    <!-- 导航栏 -->
    <view class="nav-bar">
      <view :class="['nav-item', activeTab === 'album' ? 'active' : '']" @click="changeTab('album')"
        >专辑分类</view
      >
      <view
        :class="['nav-item', activeTab === 'wallpaper' ? 'active' : '']"
        @click="changeTab('wallpaper')"
        >壁纸分类</view
      >
    </view>

    <!-- 分类展示区 -->
    <view class="classify" v-if="classifyList.length || noData">
      <theme-item v-for="item in classifyList" :key="item.id" :item="item"></theme-item>
    </view>

    <view class="loadingLayout" v-else>
      <uni-load-more :status="noData ? 'noMore' : 'loading'"></uni-load-more>
    </view>

    <view class="safe-area-inset-bottom"></view>
  </view>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShareAppMessage, onShareTimeline, onReachBottom } from '@dcloudio/uni-app'
import { apiGetClassify } from '@/api/apis.js'
import { toast } from '@/utils/common.ts'

// 数据获取和处理逻辑
const classifyList = ref([])
const activeTab = ref('album') // 默认选中专辑分类
const loadingMore = ref(false)
const noData = ref(false)
const queryParams = {
  pageNum: 1,
  pageSize: 15,
  type: 2,
}
const getClassify = async (append = false) => {
  try {
    const res = await apiGetClassify(queryParams)
    // console.log(res)
    if (!append) {
      classifyList.value = res.rows
    } else {
      classifyList.value = [...classifyList.value, ...res.rows]
    }
    if (res.rows.length < queryParams.pageSize) {
      noData.value = true
    }
  } catch (error) {
    console.error('Failed to fetch data:', error)
  } finally {
    loadingMore.value = false
  }
}

const changeTab = (tab) => {
  activeTab.value = tab
  queryParams.pageNum = 1
  noData.value = false
  if (tab === 'album') {
    queryParams.type = 2
  } else if (tab === 'wallpaper') {
    queryParams.type = 1
  }
  getClassify()
}

// 分享功能保持不变
onShareAppMessage(() => ({
  title: '咸虾米壁纸，精选分类',
  path: '/pages/classify/classify',
}))

onShareTimeline(() => ({
  title: '咸虾米壁纸，精选分类',
}))

onMounted(() => {
  getClassify()
})

// 加载更多
onReachBottom(async () => {
  if (noData.value) {
    toast('没有更多数据了')
    return
  }
  queryParams.pageNum++
  await getClassify(true)
})
</script>

<style lang="scss" scoped>
.classLayout {
  .nav-bar {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20rpx;
    padding: 10rpx 0;

    .nav-item {
      flex: 1;
      text-align: center;
      padding: 10rpx;
      cursor: pointer;
      &.active {
        color: blue; /* 当前选中的颜色 */
        border-bottom: 4rpx solid blue;
      }
    }
  }

  .classify {
    padding: 30rpx;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15rpx;
  }
}
</style>
